#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

# utility functions

import re
from types import *
import random, string

def genRandStr(strLen = 6):
	"""
	Generate a random string of letters of length strLen.
	"""
	return ''.join([random.choice(string.letters) for n in range(strLen)])


# sort a list of dictionaries by a given dict key
def sortListDict(listdict, dictkey):
	titlelist = [d[dictkey] for d in listdict]
	titledict = dict(zip(titlelist,listdict))
	newlist = [titledict[k] for k in sorted(titledict.keys())]
	return newlist

# encoding
def chkenc(data):
	if type(data) is UnicodeType:
		return data.encode('utf-8')
	elif type(data) is StringType:
		return data
	return data

def uni2asc(unistr):
	if type(unistr) is UnicodeType:
		return unistr.encode('ascii','xmlcharrefreplace')
	else:
		return data

def nl2br(plainstr):
	return plainstr.replace('\n','<br>')

# clean html tags from metadata
def cleanhtml(field):
	# NOT PRIMETIME READY  (NOT EVEN 3AM INFOMERCIAL READY)
	# tag pairs
	htmlMatch = re.compile('<(\w+)(\s+.*)?>(.*?)(</\\1>)')
	# to be honest, I never did much with this. I would delete it
	# if I didn't love the 'primetime' comment above
	field = htmlMatch.sub('\\3',field)
	return field

# getconf - get dictionary of the config file
def getconf(filename):
	vars = {}
	fh = open(filename,'r')
	for line in fh:
		# take off comments
		decom = line.split('#')[0].strip()
		# get variable
		varspl = decom.split('=')
		varnam = varspl[0].strip()
		try:
			varval = varspl[1].strip()
		except:
			varval = ''
		# if variable on line, add to dict
		if len(varnam) > 0:
			vars[varnam] = varval
	fh.close()
	return vars

# outbit - print out part of a page
def outbit(id, data = ()):
	# change to a tuple if it isn't already
	data = tuple(data)
	file = fileget('parts/' + id + '.html')
	print file % data

# fileget - get the contents of the file
def fileget(filename):
	fh = open(filename,'r')
	file = ''
	for line in fh:
		file += line
	fh.close()
	return file

# fileprint - prints content of the file
def fileprint(filename):
	fh = open(filename,'r')
	for line in fh:
		print line.strip()
	fh.close()

# put commas in large numbers
def commas(number):
	com = str(number)
	firstC = len(com) % 3
	if not firstC: firstC = 3
	firstN, restN = com[:firstC], com[firstC:]
	allN = [firstN] + [restN[c:c+3] for c in range(0,len(restN),3)]
	return ','.join(allN)

# clean user info
def cui(userStr):
	if type(userStr) not in StringTypes: return userStr
	# for injection exploits, remove ';'
	sq = re.compile(';|%3B',re.IGNORECASE)
	ap = re.compile("'|%27")
	userStr = sq.sub('&#59;',userStr)
	userStr = ap.sub('&#39;',userStr)
	return userStr

# eof

